package com.zyc.app.woa.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.zyc.app.woa.R;
import com.zyc.app.woa.SubscribeAccounts;
import com.zyc.app.woa.activity.ArticleActivity;
import com.zyc.app.woa.data.AccountInfo;
import com.zyc.app.woa.data.CachedArticle;
import com.zyc.app.woa.db.DBManager;
import com.zyc.app.woa.utils.*;
import com.zyc.app.woa.utils.Caches.CacheKey;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * Author: yingchang.zhang
 * Date  : 2014/12/18
 */
public class ArticleListFragment extends BaseFragment implements OnItemClickListener {
    private ListView mListView;
    private ArticlesAdapter mAdapter;
    private AccountInfo mAccountInfo;
    private ArrayList<CachedArticle> mCachedArticles;

    public static final int READING_ARTICLE = 100;

    public static ArticleListFragment buildInstance(AccountInfo accountInfo) {
        ArticleListFragment fragment = new ArticleListFragment();
        fragment.setAccountInfo(accountInfo);
        return fragment;
    }

    public void setAccountInfo(AccountInfo accountInfo) {
        mAccountInfo = accountInfo;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_articles, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mListView = (ListView) view.findViewById(R.id.articles_list);
        mAdapter = new ArticlesAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        mListView.setEmptyView(view.findViewById(R.id.empty_view));
        setupViews();
        loadArticles();
    }

    public void updateContent(AccountInfo accountInfo) {
        setAccountInfo(accountInfo);
        loadArticles();
        setupViews();
    }

    private void loadArticles() {
        if (null != mAccountInfo) {
            loadArticles(mAccountInfo);
        }
    }

    private void setupViews() {
        if (null != mAccountInfo) {
            setTitle(mAccountInfo.name);
        } else {
            if (0 == SubscribeAccounts.getCount()) {
                ((TextView) getView().findViewById(R.id.empty_view)).setText(R.string.add_account_helper);
            }
        }
    }

    @Override
    public String getFragmentTag() {
        return FragmentUtil.HOME_FRAGMENT;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Caches.put(CacheKey.READING_ARTICLE, mCachedArticles.get(position));
        Intent intent = new Intent(view.getContext(), ArticleActivity.class);
        startActivityForResult(intent, READING_ARTICLE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case READING_ARTICLE:
                if (Caches.getBoolean(CacheKey.CLEAR_AFTER_READ, true)) {
                    CachedArticle article = (CachedArticle) Caches.get(CacheKey.READING_ARTICLE);
                    if (!article.isFavorite()) {
                        mCachedArticles.remove(article);
                        mAccountInfo.totalArticlesNum--;
                        mAdapter.notifyDataSetChanged();
                        DBManager.deleteArticle(article);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void loadArticles(AccountInfo accountInfo) {
        mCachedArticles = DBManager.getCachedArticles(accountInfo.wxId);
        mAccountInfo.totalArticlesNum = mCachedArticles.size();
        mAdapter.notifyDataSetChanged();
//        sortArticles();
    }

    private void sortArticles() {
        Collections.sort(mCachedArticles, new Comparator<CachedArticle>() {
            @Override
            public int compare(CachedArticle lhs, CachedArticle rhs) {
                return (lhs.read + lhs.favorite) - (rhs.read + rhs.favorite);
            }
        });
        mAdapter.notifyDataSetChanged();
    }

    class ArticlesAdapter extends BaseAdapter {
        private int mNormalColor;
        private int mDisableColor;

        public ArticlesAdapter() {
            super();
            mNormalColor = CommonUtils.getColor(R.color.text_color);
            mDisableColor = CommonUtils.getColor(R.color.grey_text_color);
        }

        @Override
        public int getCount() {
            return null != mCachedArticles ? mCachedArticles.size() : 0;
        }

        @Override
        public CachedArticle getItem(int position) {
            return null != mCachedArticles ? mCachedArticles.get(position) : null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = newView(parent);
                convertView.setTag(new ViewHolder(convertView));
            }

            bindView(position, convertView);
            return convertView;
        }

        private View newView(ViewGroup parent) {
            return View.inflate(parent.getContext(), R.layout.articles_list_item, null);
        }

        private void bindView(int position, View view) {
            CachedArticle article = getItem(position);
            ViewHolder holder = (ViewHolder) view.getTag();
            if (null != holder && null != article) {
                holder.titleText.setText(article.title);
                holder.timeText.setText(CommonUtils.getTimeDiff(article.cachedTime));
                holder.timeText.setTextColor(article.read > 0 ? mDisableColor : mNormalColor);
                holder.titleText.setTextColor(article.read > 0 ? mDisableColor : mNormalColor);
                Trace.log("article: " + article.title + " read: " + article.read);
                Trace.log("article: " + article.title + " favorite: " + article.favorite);
                ViewUtil.loadPicForImageView(article.imgLink, holder.headerImage, R.drawable.default_pic);
                view.setTag(R.id.view_bind_data, article);
            }
        }

        class ViewHolder {

            public ViewHolder(View view) {
                titleText = (TextView) view.findViewById(R.id.article_name);
                timeText = (TextView) view.findViewById(R.id.article_update_time);
                headerImage = (ImageView) view.findViewById(R.id.article_image);
            }

            TextView titleText;
            TextView timeText;
            ImageView headerImage;
        }
    }
}
